package cn.stylefeng.guns.core.schedule;

import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.MessageType;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyWx;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.service.BtyInventoryService;
import cn.stylefeng.guns.sys.modular.system.service.BtyWxService;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.DsstoreBillService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
public class ScheduledTask {
    private Logger logger = LoggerFactory.getLogger(ScheduledTask.class);
    @Resource
    private DictService dictService;
    @Resource
    private BtyWxService btyWxService;
    @Resource
    private BtyInventoryService btyInventoryService;
    @Resource
    private DsstoreBillService dsstoreBillService;

    /**
     * 每10分钟执行一次
     * cron表达式执行
     * 获取公众号access_token
     */
   //@Scheduled(cron = "0 0/10 * * * ?")
    public void getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx373650bf8de7f27d&secret=d3e9c259a6dbca1c5ef73beb1804f3c7";
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        String accessToken = jsonObject.get("access_token").toString();
        Dict dict1 = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        if (ToolUtil.isNotEmpty(dict1)) {
            dict1.setName(accessToken);
            dictService.updateById(dict1);
        } else {
            Dict dict = new Dict();
            dict.setDictId(UUIDUtils.getId());
            Long id = 1289070054131363842L;
            dict.setDictTypeId(id);
            dict.setParentId(0L);
            dict.setStatus("ENABLE");
            dict.setCode("access_token");
            dict.setName(accessToken);
            dictService.save(dict);
        }
        logger.info("====access_token====" + accessToken);
    }


    /**
     * 获取前一天的门店(中心)库存流水集市写入库中
     */

    //@Scheduled(cron = "0 0/10 * * * ?")
    public void getDsstorebill() {
        Date date = new Date();
        //获取前一天的数据
        String yearstoday = DateUtil.getYearstoday(date);

        logger.info("门店库存流水定时任务-开始执行,日期：{}", date);
        Integer dataCount = btyInventoryService.getDsstorebillAndInsert(yearstoday);
        logger.info("门店库存流水定时任务-结束执行,日期：{},写入库数量：{}", date,dataCount);
    }
    //@Scheduled(cron = "0 0/10 * * * ?")
    public void initDsstorebillData() {
        Date date = new Date();
        //获取前一天的数据
        String yearstoday = DateUtil.getYearstoday(date);

        logger.info("门店库存流水定时任务-开始执行数据写入,日期：{}", date);
        Integer dataCount = dsstoreBillService.initDsstorebillData(yearstoday);
        logger.info("门店库存流水定时任务-结束执行数据写入,日期：{},写入库数量：{}", date,dataCount);
    }
//    @Scheduled(cron = "30 41 14 * * ?")
     //每周1,周五早上 8点触发
    //@Scheduled(cron = "0 00 8 ? * MON,FRI")
    public void sendMessage(){
        logger.info("====定时推送消息开始===start====");
        RestTemplate restTemplate = new RestTemplate();
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }
        //通过openid给指定用户发送消息
        String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
        String s="";
        //财务部27 人事部1268783244079915009  技术部25
        //List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>().in("openid",new Object[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"}));
//       List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>(). notIn("dept_id",new Object[]{"25"}));
        List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>());
        for (int i = 0; i <wxList.size() ; i++) {
            String toUser=wxList.get(i).getOpenid();
            String msgType = MessageType.TEXT_MESSAGE;
            JSONObject contentJson = new JSONObject();
            String name=wxList.get(i).getName()==null?"":wxList.get(i).getName();
            String content="周末转瞬到眼前，发个祝福送祝愿：愿你休闲娱乐心情欢，亲\n" +
                    "友聚会喜开颜，周末轻松乐满满，下周工作更顺意，工资奖金成倍\n" +
                    "番。预祝你周末愉快！附赠早安，"+name+"同学，也许你会愿意和我聊聊天？";
            contentJson.put("content",content);
            JSONObject json = new JSONObject();
            json.put("touser", toUser);
            json.put("msgtype", msgType);
            json.put("text", contentJson);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);

            s= restTemplate.postForEntity(url,formEntity,String.class).getBody();
            s=toUser+s;
            logger.info("===openid==="+s);
        }
        logger.info("====定时推送消息结束===end====");
    }

}
